<template>
  <div class="w-full h-full">
    <!-- <mci-dialog
      v-model="visible"
      :title="title"
      width="1000"
      top="10vh"
      draggable
      :confirm-handle="handleConfirm"
      @close="handleClosed"
    > -->
    <div class="flex justify-center">
      <div class="w-1/2">
        <mci-steps :active="activeStep" finish-status="success">
          <mci-step title="普通数据集配置" />
          <mci-step title="普通数据集测试" />
        </mci-steps>
      </div>
    </div>
    <div style="height: 50vh; overflow-y: auto">
      <FormMode :mode="'edit'">
        <div v-show="activeStep === 0">
          <mci-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" label-position="top">
            <!-- 接口名称 -->
            <mci-row>
              <mci-col :span="12">
                <mci-form-item label="接口名称" prop="dataModelName">
                  <mci-input
                    v-model="ruleForm.dataModelName"
                    type="text"
                    :maxlength="INPUT_MAX_DATA_MODEL_NAME"
                    :placeholder="`请填写`"
                    style="width: calc(100% - 16px)"
                  />
                </mci-form-item>
              </mci-col>
              <!-- 表名称 -->
              <mci-col :span="12">
                <mci-form-item label="表名称" prop="tableID">
                  <mci-select
                    v-model="ruleForm.tableID"
                    :list="tableOptions"
                    placeholder="请选择"
                    style="width: calc(100% - 16px)"
                    :disabled="dataModelID"
                  />
                </mci-form-item>
              </mci-col>
            </mci-row>

            <mci-row>
              <!--查询列 -->
              <mci-col :span="24">
                <mci-form-item label="查询列" prop="columns">
                  <mci-select
                    v-model="ruleForm.columns"
                    :multiple="true"
                    class="w-full"
                    :disabled="!ruleForm.tableID"
                    :collapse-tags="true"
                    :max-collapse-tags="3"
                    collapse-tags-tooltip
                    style="width: calc(100% - 16px)"
                  >
                    <template #header>
                      <mci-checkbox v-model="checkAll" :indeterminate="true" @change="handleCheckAll"> 全选 </mci-checkbox>
                    </template>
                    <mci-option
                      v-for="option in columnOptions"
                      :key="option.varName"
                      :label="option.varLabel"
                      :value="option.varName"
                      :disabled="option.disabled"
                    />
                  </mci-select>
                </mci-form-item>
              </mci-col>
            </mci-row>

            <!-- 参数设置 -->
            <mci-form-item label="参数设置" prop="parameters">
              <!-- <AddBtn btn-text="新增参数" @add="addParam" /> -->
              <ParametersAdd ref="parametersAddRef" class="mt-4" style="width: calc(100% - 16px)" />
            </mci-form-item>

            <!-- 条件设置 -->
            <!-- <mci-form-item label="条件设置" prop="conditions">
          <AddBtn btn-text="新增条件" @add="addCond" />
          <CondsAdd ref="condAddRef" />
        </mci-form-item> -->

            <!-- 条件设置 -->
            <mci-form-item label="条件设置" prop="conditions">
              <div class="w-full pb-8 pt-0 bg-fill-2 min-h-100 mt-4" style="width: calc(100% - 16px)">
                <Conditions
                  ref="conditionsRef"
                  v-model="ruleForm.conditions"
                  :variable-options="variableOptions"
                  class="w-full"
                  :left-options="leftOptions"
                />
              </div>
            </mci-form-item>
          </mci-form>
        </div>
        <div v-show="activeStep === 1" style="width: calc(100% - 16px)">
          <div class="py-8 flex flex-col">
            <TestReq :data="testReqData" @change="handleTestReqChange" />
            <div class="flex justify-end mt-8">
              <mci-button plain type="primary" @click="execute">执行</mci-button>
            </div>
          </div>
          <div>
            <TestRes :table-data="tesResTableData" :table-column="tesResTableColumn" />
          </div>
        </div>
      </FormMode>
    </div>
    <!-- <template #footer>
        <span class="dialog-footer">
          <mci-button @click="visible = false">取消</mci-button>
          <mci-button v-show="activeStep" @click="last"> 上一步 </mci-button>
          <mci-button v-show="activeStep === 0" type="primary" @click="next"> 下一步 </mci-button>
          <mci-button v-show="activeStep === 1" type="primary" @click="handleConfirm"> 确定 </mci-button>
        </span>
      </template>
    </mci-dialog> -->
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
// import { ElSpace } from 'element-plus';
import {
  MciButton,
  MciInput,
  MciForm,
  MciFormItem,
  MciSelect,
  MciOption,
  MciCol,
  MciRow,
  MciMessage,
  MciStep,
  MciSteps,
  MciCheckbox
} from '@/components/base';
import { FormMode } from '@/components/base/Form/mode';
import type { RuleForm, TableOption } from './data';
import { INPUT_MAX_DATA_MODEL_NAME, VarType, dataModelKey } from './data';
// import AddBtn from '../AddBtn/index.vue';
import ParametersAdd from '../ParametersAdd/index.vue';
import TestReq from '../TestReq/index.vue';
import TestRes from '../TestRes/index.vue';
// import CondsAdd from '@/views/comps/condsAdd/index.vue';
import { Conditions } from '@/components/business/Conditions';

import {
  getTableList,
  getTableFields,
  postDataCfgAdd,
  postDataCfgUpdate,
  postDataCfgGet,
  postDataCfgExecute
} from '@/api/decision-engine';
import type {
  IGetTableListRes,
  IGetTableFieldsReq,
  IGetTableFieldsRes,
  IPostDataCfgAddReq,
  IPostDataCfgAddRes,
  IPostDataCfgUpdateReq,
  // IPostDataCfgUpdateRes,
  IPostDataCfgGetReq,
  IPostDataCfgGetRes,
  IPostDataCfgExecuteReq,
  IPostDataCfgExecuteRes
} from '@/api/decision-engine';
import { ILeft, IVariable } from '@/components/business/Conditions/type';
import { CheckboxValueType } from 'element-plus';

// const props = defineProps({
//   rowId: {
//     type: String,
//     default: ''
//   }
// });
const emit = defineEmits(['init', 'activeStep', 'closed']);

// const formMode = useFormMode();

onMounted(() => {
  emit('init');
});

const variableOptions = ref<IVariable[]>([]);
const leftOptions = ref<ILeft[]>([]);
const visible = ref(false);
const title = ref('新增普通数据集');
const dataModelID = ref();
// const handleClosed = () => {
//   emit('closed');
// };

const activeStep = ref(0);

// 表单
const ruleFormRef = ref<any>();
const ruleForm = reactive<RuleForm>({
  dataModelName: '',
  tableID: '',
  columns: [],
  parameters: [],
  conditions: {}
});

// 条件校验
const validateConditions = (rule: any, value: any, callback: any) => {
  if (ruleForm.conditions && ruleForm.conditions.conditions && ruleForm.conditions.conditions.length) {
    callback();
  } else {
    callback(new Error('请添加条件'));
  }
};
const rules = reactive<any>({
  dataModelName: [
    { required: true, message: '请填写接口名称', trigger: 'blur' }
    // { required: true, validator: validateTarget, trigger: 'blur' }
  ],
  tableID: [
    { required: true, message: '请选择表', trigger: 'blur' }
    // { required: true, validator: validateTarget, trigger: 'blur' }
  ],
  parameters: [
    // { required: true, message: '请完成参数设置的必填内容', trigger: 'blur' }
  ],
  conditions: [{ required: true, validator: validateConditions, trigger: 'blur' }]
});
// 列
const checkAll = ref(false);
const handleCheckAll = (val: CheckboxValueType) => {
  // indeterminate.value = false
  if (val) {
    ruleForm.columns = columnOptions.value.map((_) => _.varName);
  } else {
    ruleForm.columns = [];
  }
};
const tableOptions = ref<TableOption[]>([]);
const columnOptions = ref<TableOption[]>([]);
let columnOptionsDisabled: string[] = [];

const parametersAddRef = ref<any>(null);
// const condAddRef = ref<any>(null);
// 条件
const conditionsRef = ref<any>();
// const addParam = () => {
//   parametersAddRef.value?.addRow();
// };

// const addCond = () => {
//   condAddRef.value?.addRow();
// };

// 表格数据请求
const tableRequest = async () => {
  const data: IGetTableListRes = await getTableList();
  if (data) {
    tableOptions.value = data.map((item: string) => {
      return {
        label: item,
        value: item
      };
    });
  } else {
    tableOptions.value = [];
  }
};
tableRequest();

// 列
const columnRequest = async () => {
  if (!ruleForm.tableID) return;
  const params: IGetTableFieldsReq = {
    tableName: ruleForm.tableID
  };
  const data: IGetTableFieldsRes = await getTableFields(params);

  if (data) {
    columnOptions.value = data.map((item) => {
      return {
        ...item,
        disabled: columnOptionsDisabled.find((_item) => _item === item.varName) ? true : false
      };
    });
    leftOptions.value = data.map((item: any) => {
      return {
        label: item.varLabel ? item.varLabel : item.varName,
        value: item.varName
      };
    });
  }
};

watch(
  [() => ruleForm.tableID, () => ruleForm.parameters],
  ([tableID, parameters], [oldTableID]) => {
    if (tableID !== oldTableID) {
      if (!dataModelID.value) {
        ruleForm.columns = [];
      }
      tableID && columnRequest();
    }

    const arr = [];
    if (parameters) {
      for (const iterator of parameters) {
        if (iterator && iterator.varName && iterator.varLabel) {
          arr.push({
            label: iterator.varLabel,
            value: iterator.varName
          });
        }
      }
    }
    variableOptions.value = arr;
  },
  { deep: true }
);

// 下一步
const next = () => {
  testReqData.value = [];
  const { parameters } = parametersAddRef.value?.getData();
  if (parameters) {
    testReqData.value = parameters.map((item: any) => {
      return {
        ...item,
        value: item.initValue || item.initValue === 0 ? item.initValue : ''
      };
    });
  }
  formValidate();
};

// 上一步
const last = () => {
  activeStep.value > 0 && activeStep.value--;
  emit('activeStep', activeStep.value);
};

// 执行参数
const testReqData = ref([]);
const testReqResult = ref<any>([]);
// 执行返回
const tesResTableData = ref<any>([]);
const tesResTableColumn = ref<any>([]);

const handleTestReqChange = (value: any) => {
  testReqResult.value = value;
};

// 执行
const execute = () => {
  exeRequest();
};

// 执行请求
const exeRequest = async () => {
  const { conditions, conjs, splitIndexes } = ruleForm.conditions;

  const { parameters } = parametersAddRef.value?.getData();
  const { dataModelName, tableID, columns } = ruleForm;
  const paramsObj: any = {};
  if (testReqResult.value) {
    for (const iterator of testReqResult.value) {
      if (iterator) {
        paramsObj[iterator.varName] = iterator.value ? iterator.value : iterator.initValue;
      }
    }
  }
  const params: IPostDataCfgExecuteReq = {
    cfgName: dataModelName,
    tableName: tableID,
    // conditions: {
    //   conditions,
    //   conjs
    // },
    columns,
    variables: parameters,
    params: paramsObj
  };
  if (conditions && conditions.length) {
    params.conditions = {
      conditions,
      conjs,
      splitIndexes
    };
  }

  const data: IPostDataCfgExecuteRes = await postDataCfgExecute(params);
  // 执行
  tesResTableData.value = [];
  tesResTableColumn.value = [];
  if (data) {
    const { results, variables } = data;
    if (results) tesResTableData.value = results;
    if (variables) {
      tesResTableColumn.value = variables.map((item: any) => {
        return {
          prop: item.varName,
          label: item.varLabel ? item.varLabel : item.varName
        };
      });
    }
  }
};

//  update参数
const updateParameters = (newVal: any) => {
  ruleForm.parameters = newVal;
};
provide(dataModelKey, { columnOptions, ruleForm, updateParameters });

const formValidate = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid: any, fields: any) => {
    if (valid) {
      if (activeStep.value === 0) {
        activeStep.value === 0 && activeStep.value++;
        emit('activeStep', activeStep.value);
      }
    } else {
      if (fields) {
        const keys = Object.keys(fields) || [];
        for (const key of keys) {
          if (key && fields[key]) {
            for (const item of fields[key]) {
              if (item && item.message) {
                MciMessage({
                  message: item.message,
                  type: 'warning'
                });
                return;
              }
            }
          }
        }
      }
    }
  });
};

// 新增请求
const addRequest = async () => {
  // const { conditions, conjs } = condAddRef.value?.getData();
  // const { conditions, conjs } = conditionsRef.value?.getData();
  const { conditions, conjs, splitIndexes } = ruleForm.conditions;

  const { parameters } = parametersAddRef.value?.getData();
  const { dataModelName, tableID, columns } = ruleForm;
  const params: IPostDataCfgAddReq = {
    cfgName: dataModelName,
    tableName: tableID,
    conditions: {
      conditions,
      conjs,
      splitIndexes
    },
    columns,
    variables: parameters
  };
  const data: IPostDataCfgAddRes = await postDataCfgAdd(params);
  if (data) {
    // 新增成功
    visible.value = false;
    emit('closed', true);
  }
};

// 修改请求
const modifyRequest = async () => {
  // const { conditions, conjs } = condAddRef.value?.getData();
  const { conditions, conjs, splitIndexes } = ruleForm.conditions;
  const { parameters } = parametersAddRef.value?.getData();
  const { dataModelName, columns } = ruleForm;
  const params: IPostDataCfgUpdateReq = {
    id: dataModelID.value,
    cfgName: dataModelName,
    conditions: {
      conditions,
      conjs,
      splitIndexes
    },
    columns,
    variables: parameters
  };
  postDataCfgUpdate(params).then(() => {
    visible.value = false;
    emit('closed', true);
  });
  // if (data) {
  // 修改成功
  // visible.value = false;
  // }
};

// 确定操作
const handleConfirm = () => {
  if (dataModelID.value) {
    modifyRequest();
  } else {
    addRequest();
  }
};

// 初始化
const initData = async (dataModel?: any) => {
  visible.value = true;
  dataModelID.value = dataModel?.id;
  activeStep.value = 0;
  emit('activeStep', activeStep.value);
  tesResTableData.value = [];
  tesResTableColumn.value = [];
  // 回显
  if (dataModelID.value) {
    title.value = '修改普通数据集';
    ruleForm.dataModelName = dataModel?.cfgName;
    // ruleForm.tableID = dataModel?.tableName;
    // ruleForm.columns = dataModel?.columns;
    // 从详情接口获取
    const params: IPostDataCfgGetReq = {
      id: dataModelID.value
    };

    const data: IPostDataCfgGetRes = await postDataCfgGet(params);
    if (data) {
      let arr: any[] = [];
      if (data?.variables) {
        arr = data.variables
          .filter((item) => item.scope === 'REQUEST')
          ?.map((item) => {
            if (
              item &&
              item.initValue &&
              typeof item.initValue === 'string' &&
              (item.varType === VarType.Date || item.varType === VarType.DateTime)
            ) {
              item.initValue = parseInt(item.initValue);
            }
            return item;
            });
      }
      parametersAddRef.value?.initData(arr);
      // condAddRef.value?.initData(parseConditions, data?.conditions?.conjs);
      ruleForm.conditions = {
        conditions: data?.conditions?.conditions,
        conjs: data?.conditions?.conjs,
        splitIndexes: data?.conditions?.splitIndexes
      };
      ruleForm.columns = data.columns || [];
      if (data.columns && data.columns.length > 0) {
        columnOptionsDisabled = [...data.columns];
      } else {
        columnOptionsDisabled = [];
      }
      if (data.tableName) {
        ruleForm.tableID = data.tableName;
        columnRequest();
      }
    }
  } else {
    title.value = '新增普通数据集';

    // await nextTick();
    // await ruleFormRef?.value?.reset();
    ruleForm.dataModelName = '';
    ruleForm.tableID = '';
    ruleForm.columns = [];
    parametersAddRef.value?.initData();
    // condAddRef.value?.initData();
    ruleForm.conditions = {};
    columnOptionsDisabled = [];
  }
};

defineExpose({
  initData,
  next,
  last,
  handleConfirm
});
</script>
